package com.team.databoard.controller;

import com.team.databoard.common.BaseResponse;
import com.team.databoard.common.ErrorCode;
import com.team.databoard.common.ResultUtils;
import com.team.databoard.exception.BusinessException;
import com.team.databoard.model.User;
import com.team.databoard.model.request.UserRequest;
import com.team.databoard.service.impl.UserServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.team.databoard.constant.UserConstant.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserServiceImpl userService;

    @PostMapping("/login")
    public BaseResponse<Boolean> login(@RequestBody UserRequest userRequest, HttpServletRequest request) {
        // 参数校验
        if (userRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userName = userRequest.getUserName();
        String password = userRequest.getPassword();
        if (StringUtils.isAnyBlank(userName, password)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "用户名或密码不能为空");
        }
        if (userService.login(userName, password, request)) {
            return ResultUtils.success(true);
        }
        return ResultUtils.error(ErrorCode.PARAMS_ERROR, "用户名或密码错误");
    }

    @PostMapping("/logout")
    public BaseResponse<Boolean> logout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return ResultUtils.success(true);
    }

    @GetMapping("/list")
    public BaseResponse<List<User>> listUsers(HttpServletRequest request) {
        if (request.getSession().getAttribute(USER_LOGIN_STATE) == null) {
            return ResultUtils.error(ErrorCode.NOT_LOGIN);
        }
        return ResultUtils.success(userService.list().stream().peek(user -> user.setPassword(null)).toList());
    }

    @GetMapping("/current")
    public BaseResponse<User> currentUser(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null) {
            return ResultUtils.error(ErrorCode.NOT_LOGIN);
        }
        return ResultUtils.success(user);
    }

    @PostMapping("/add")
    public BaseResponse<Integer> addUser(@RequestBody UserRequest userRequest, HttpServletRequest request) {
        // 权限校验
        if (!isAdmin(request)) {
            return ResultUtils.error(ErrorCode.NO_AUTH);
        }
        // 参数校验
        if (userRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userName = userRequest.getUserName();
        String password = userRequest.getPassword();
        if (StringUtils.isAllBlank(userName, password)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "用户名和密码不能为空");
        }
        int role;
        if (userRequest.getRole() != null) {
            role = userRequest.getRole();
            if (role != 0 && role != 1) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "角色只能为0或1");
            }
        } else {
            role = DEFAULT_ROLE;
        }
        return ResultUtils.success(userService.insertUser(userName, password, role));
    }

    @DeleteMapping("/{id}")
    public BaseResponse<Boolean> deleteUser(@PathVariable(value = "id") int id, HttpServletRequest request) {
        // 权限校验
        if (!isAdmin(request)) {
            return ResultUtils.error(ErrorCode.NO_AUTH);
        }
        if (userService.deleteUser(id)) {
            return ResultUtils.success(true);
        }
        return ResultUtils.error(ErrorCode.PARAMS_ERROR);
    }

    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody UserRequest userRequest, HttpServletRequest request) {
        // 参数校验
        if (userRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        if (userRequest.getId() == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "用户id不能为空");
        }
        int id = userRequest.getId();
        User user = userService.getById(id);
        // 权限校验
        if (!isAdmin(request)) {
            User currentUser = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
            // 判断是否为当前用户，当前用户只能更新自己的用户名和密码，不能更新角色
            if (currentUser == null || !currentUser.getId().equals(id) || userRequest.getRole() == ADMIN_ROLE) {
                return ResultUtils.error(ErrorCode.NO_AUTH);
            }
        }
        String userName;
        if (userRequest.getUserName() != null) {
            userName = userRequest.getUserName();
            if (StringUtils.isBlank(userName)) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "用户名不能为空");
            }
        } else {
            userName = user.getUserName();
        }
        String password;
        // 判断是否更新密码
        if (userRequest.getPassword() != null) {
            if (StringUtils.isBlank(userRequest.getPassword())) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "密码不能为空");
            }
            password = userService.encryptPassword(userRequest.getPassword());
        } else {
            password = user.getPassword();
        }
        int role;
        // 判断是否更新角色
        if (userRequest.getRole() != null) {
            if (userRequest.getRole() != 0 && userRequest.getRole() != 1) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "角色只能为0或1");
            }
            role = userRequest.getRole();
        } else {
            role = user.getRole();
        }
        if (userService.updateUser(id, userName, password, role)) {
            // 如果更新的是当前用户，更新session中的用户信息
            if (id == ((User) request.getSession().getAttribute(USER_LOGIN_STATE)).getId()) {
                request.getSession().setAttribute(USER_LOGIN_STATE, userService.getById(id));
            }
            return ResultUtils.success(true);
        }
        return ResultUtils.error(ErrorCode.PARAMS_ERROR);
    }

    /**
     * 检验用户是否为管理员
     *
     * @param request http请求
     * @return 是否为管理员
     */
    private boolean isAdmin(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        return user != null && user.getRole() == ADMIN_ROLE;
    }
}
